﻿Imports MetodosComuns
Imports extranet.BC
Imports extranet.BE
Imports System.Collections.Generic
Imports System.IO

Partial Class Eventos_AdmEvtGerenciamentoEvento
    Inherits System.Web.UI.Page
    Const STRENDERECOBANNERSERVIDOR As String = ".\banners\"
    Const STRENDERECOURL As String = "http://extranet.fit4.com.br/Eventos/Evento.aspx"
    Protected Sub btnSalvar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSalvar.Click
        Dim odOrdemTelas As New OrderedDictionary
        Dim objBEEvento As BEEvento
        Dim lstTelas As List(Of BETelaEvento) = Session("TelasEvento")

        If RecolheCampos(lstTelas) Then
            objBEEvento = BCEvento.SelecionarEvento(lblId.Text)
            objBEEvento.StatusEvento = IIf(chbAtivo.Checked, "Ativo", "Inativo")
            objBEEvento.DtFim = New Date(Convert.ToInt32(txtDtFim.Text.Split("/")(2)), Convert.ToInt32(txtDtFim.Text.Split("/")(1)), Convert.ToInt32(txtDtFim.Text.Split("/")(0)))
            objBEEvento.DtInicio = New Date(Convert.ToInt32(txtDtInicio.Text.Split("/")(2)), Convert.ToInt32(txtDtInicio.Text.Split("/")(1)), Convert.ToInt32(txtDtInicio.Text.Split("/")(0)))
            objBEEvento.Nome = txtNome.Text
            objBEEvento.TelasEvento = lstTelas
            Try
                'Verifica se o usuario colocou banner
                If FileUpload1.HasFile Then
                    Dim strNovoBanner As String
                    strNovoBanner = FileUpload1.FileName()
                    strNovoBanner = "banner_" & lblId.Text & IIf(strNovoBanner.IndexOf(".") > 0, strNovoBanner.Substring(strNovoBanner.IndexOf(".")), "")
                    Try
                        File.Delete(HttpContext.Current.Server.MapPath("~/imagens/banner/") & strNovoBanner)
                    Catch ex As ApplicationException

                    End Try
                    FileUpload1.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~/imagens/banner/") & strNovoBanner)
                    objBEEvento.Banner = strNovoBanner
                End If

                BCEvento.SalvarEvento(objBEEvento)

                System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf)
                System.Web.HttpContext.Current.Response.Write("alert(""Evento Salvo com Sucesso!"")" & vbCrLf)
                System.Web.HttpContext.Current.Response.Write("</SCRIPT>")
            Catch ex As ApplicationException
                System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf)
                System.Web.HttpContext.Current.Response.Write("alert(""Erro Salvando o Evento: " & ex.Message & """)" & vbCrLf)
                System.Web.HttpContext.Current.Response.Write("</SCRIPT>")
            End Try
        End If
    End Sub

    Protected Sub btnSalvarEEditarTelas_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSalvarEEditarTelas.Click
        Dim objBEEvento As New BEEvento
        Dim strIdEvento As String
        objBEEvento.StatusEvento = IIf(chbAtivo.Checked, "Ativo", "Inativo")
        objBEEvento.DtFim = New Date(Convert.ToInt32(txtDtFim.Text.Split("/")(2)), Convert.ToInt32(txtDtFim.Text.Split("/")(1)), Convert.ToInt32(txtDtFim.Text.Split("/")(0)))
        objBEEvento.DtInicio = New Date(Convert.ToInt32(txtDtInicio.Text.Split("/")(2)), Convert.ToInt32(txtDtInicio.Text.Split("/")(1)), Convert.ToInt32(txtDtInicio.Text.Split("/")(0)))
        objBEEvento.Nome = txtNome.Text
        objBEEvento.Banner = ""
        objBEEvento.TelasEvento = BCTelaEvento.CriarNovasTelasPadrao()
        strIdEvento = BCEvento.SalvarEvento(objBEEvento)

        If FileUpload1.HasFile Then
            Dim strNovoBanner As String
            Dim objBEEventoCriado As BEEvento = BCEvento.SelecionarEvento(strIdEvento)
            strNovoBanner = FileUpload1.FileName()
            strNovoBanner = "banner_" & strIdEvento & IIf(strNovoBanner.IndexOf(".") > 0, strNovoBanner.Substring(strNovoBanner.IndexOf(".")), "")
            Try
                File.Delete(HttpContext.Current.Server.MapPath("~/imagens/banner/") & strNovoBanner)
            Catch ex As ApplicationException

            End Try
            FileUpload1.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~/imagens/banner/") & strNovoBanner)
            objBEEventoCriado.Banner = strNovoBanner
            BCEvento.SalvarEvento(objBEEventoCriado)
        End If

        InicializarAlteracaoEvento(strIdEvento)
    End Sub

    Protected Sub btnExcluir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExcluir.Click
        Try
            BCEvento.DeletarEvento(lblId.Text)
            System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf)
            System.Web.HttpContext.Current.Response.Write("alert(""Evento Excluído com Sucesso!"")" & vbCrLf)
            System.Web.HttpContext.Current.Response.Write("</SCRIPT>")
            Response.Redirect("AdmEvtListaEventos.aspx")
        Catch ex As ApplicationException
            System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=""JavaScript"">" & vbCrLf)
            System.Web.HttpContext.Current.Response.Write("alert(""Erro Excluindo o Evento: " & ex.Message & """)" & vbCrLf)
            System.Web.HttpContext.Current.Response.Write("</SCRIPT>")
        End Try

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        '==================       PROCEDIMENTO  PADRÃO  SEGURANÇA     =============================
        Dim objBESeguranca As BESeguranca
        Dim objBEUsuario As BEUsuario = Session("objBEUsuario")
        If IsNothing(objBEUsuario) Then Response.Redirect(TELA_LOGOUT)
        Session("strTela") = MetodosComuns.GetCurrentPageName()
        If Not IsPostBack Then          ' SEGURANÇA
            objBESeguranca = BCSeguranca.SelecionaPermissoes(objBEUsuario.GrupoAcesso, Session("strTela"))
            If Not objBESeguranca.Autorizado Then Response.Redirect(TELA_LOGOUT)
            Session("objBESeguranca") = objBESeguranca
        Else
            objBESeguranca = Session("objBESeguranca")
        End If

        If Not IsPostBack Then
            Dim strIdEvento As String = Request.QueryString("Evento")
            If strIdEvento = "" Then
                InicializarInclusaoEvento()
            Else
                InicializarAlteracaoEvento(strIdEvento)
            End If
        End If
    End Sub
    Private Sub InicializarAlteracaoEvento(ByVal strIdEvento As String)
        lblTitulo.Text = "Alteração de Evento"
        btnSalvarEEditarTelas.Visible = False
        panTelas.Visible = True
        lblCaptionId.Visible = True
        lblId.Visible = True
        lblCaptionURL.Visible = True
        hlUrl.Visible = True
        lblId.Text = strIdEvento
        PreencheEvento(strIdEvento)
    End Sub
    Private Sub InicializarInclusaoEvento()
        lblTitulo.Text = "Inclusão de Evento"
        btnSalvarEEditarTelas.Visible = True
        panTelas.Visible = False
        lblCaptionId.Visible = False
        lblId.Visible = False
        lblCaptionURL.Visible = False
        hlUrl.Visible = False
        imgBanner.Visible = False
    End Sub
    Private Sub PreencheEvento(ByVal strIdEvento As String)
        Dim objBEEvento As BEEvento = BCEvento.SelecionarEvento(strIdEvento)
        txtDtFim.Text = objBEEvento.DtFim.ToString("dd/MM/yyyy")
        txtDtInicio.Text = objBEEvento.DtInicio.ToString("dd/MM/yyyy")
        hlUrl.NavigateUrl = "Evento.aspx?Id=" & objBEEvento.IdEvento
        hlUrl.Text = STRENDERECOURL & "?Id=" & objBEEvento.IdEvento
        txtNome.Text = objBEEvento.Nome
        If objBEEvento.Banner <> "" Then
            imgBanner.Visible = True
            imgBanner.ImageUrl = "~/imagens/banner/" & objBEEvento.Banner
        End If
        chbAtivo.Checked = IIf(objBEEvento.StatusEvento = "Ativo", True, False)
        Session("TelasEvento") = objBEEvento.TelasEvento
        PreencheGridView(objBEEvento.TelasEvento)
    End Sub
    Private Sub PreencheGridView(ByVal lstBETelaEvento As List(Of BETelaEvento))
        Dim ddl As DropDownList
        grvPaginas.DataSource = lstBETelaEvento
        grvPaginas.DataBind()
        For i As Integer = 0 To lstBETelaEvento.Count - 1
            ddl = grvPaginas.Rows(i).FindControl("ddlOrdem")
            ddl.Items.Clear()
            ddl.Items.Add(New ListItem("-", "0"))
            For j As Integer = 1 To grvPaginas.Rows.Count
                ddl.Items.Add(New ListItem(j.ToString(), j.ToString()))
            Next
            ddl.SelectedIndex = Convert.ChangeType(lstBETelaEvento(i).Ordem, TypeCode.Int32)
        Next
    End Sub
    Protected Sub ddlOrdem_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ddl As DropDownList = DirectCast(sender, DropDownList)
        If ddl.Items.Count = 0 Then
            ddl.Items.Clear()
            ddl.Items.Add(New ListItem("-", "0"))
            For i As Integer = 1 To grvPaginas.Rows.Count
                ddl.Items.Add(New ListItem(i.ToString(), i.ToString()))
            Next
        End If
    End Sub

    Protected Sub ddlOrdem_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        'Dim odOrdemTelas As New OrderedDictionary

        'For i As Integer = 1 To grvPaginas.Rows.Count
        '    odOrdemTelas.Add(i, "")
        'Next

        'For i As Integer = 1 To grvPaginas.Rows.Count
        '    Dim ddl As DropDownList = grvPaginas.Rows(i - 1).FindControl("ddlOrdem")

        '    If ddl.SelectedValue <> 0 Then
        '        odOrdemTelas(i) = grvPaginas.Rows(i - 1).DataItem
        '    End If
        'Next

    End Sub

    Private Function RecolheCampos(ByRef lstTelasEvento As List(Of BETelaEvento)) As Boolean
        Dim lstCamposComOrdemIgual As New List(Of Integer)
        Dim lstCamposNaoMostrados As New List(Of String)
        Dim odOrdemTelas As New OrderedDictionary
        Dim boolErro As Boolean = False

        'Contabiliza quantos serão mostrados
        For i As Integer = 0 To grvPaginas.Rows.Count - 1
            Dim ddl As DropDownList = grvPaginas.Rows(i).FindControl("ddlOrdem")
            Dim lblErro As Label = grvPaginas.Rows(i).FindControl("lblErro")
            lblErro.Visible = False
            If ddl.SelectedValue <> 0 Then
                If odOrdemTelas.Contains(ddl.SelectedValue) Then
                    If Not lstCamposComOrdemIgual.Contains(grvPaginas.DataKeys(i).Value.ToString()) Then
                        lstCamposComOrdemIgual.Add(grvPaginas.DataKeys(i).Value.ToString())
                    End If
                    If Not lstCamposComOrdemIgual.Contains(odOrdemTelas(ddl.SelectedValue).ToString()) Then
                        lstCamposComOrdemIgual.Add(odOrdemTelas(ddl.SelectedValue).ToString())
                    End If
                Else
                    odOrdemTelas.Add(ddl.SelectedValue, grvPaginas.DataKeys(i).Value.ToString())
                End If
            Else
                lstCamposNaoMostrados.Add(grvPaginas.DataKeys(i).Value.ToString())
            End If
        Next

        If lstCamposComOrdemIgual.Count = 0 Then
            'Usuario entrou com ordem certa
            'Preencho telas
            err.IsValid = True
            For Each objTelaEvento As BETelaEvento In lstTelasEvento
                For Each de As DictionaryEntry In odOrdemTelas
                    If objTelaEvento.IdTela.ToString = de.Value.ToString Then
                        objTelaEvento.Ordem = Convert.ToInt32(de.Key.ToString())
                        objTelaEvento.Mostra = True
                    End If
                Next
                For Each strCampoNaoMostrado As String In lstCamposNaoMostrados
                    If objTelaEvento.IdTela.ToString = strCampoNaoMostrado Then
                        objTelaEvento.Ordem = 0
                        objTelaEvento.Mostra = False
                    End If
                Next
            Next
        Else
            err.IsValid = False
            For i As Integer = 0 To grvPaginas.Rows.Count - 1
                If lstCamposComOrdemIgual.Contains(grvPaginas.DataKeys(i).Value.ToString()) Then
                    Dim lblErro As Label = grvPaginas.Rows(i).FindControl("lblErro")
                    lblErro.Visible = True
                End If
            Next
            boolErro = True
        End If
        Return Not boolErro
    End Function

    Protected Sub lnkAdicionar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkAdicionar.Click
        Dim lstTelas As List(Of BETelaEvento) = Session("TelasEvento")
        BCTelaEvento.IncluirNovaTela(lstTelas, txtNovaTela.Text)
        Session("TelasEvento") = lstTelas
        PreencheGridView(lstTelas)
        txtNovaTela.Text = ""
    End Sub

    Protected Sub btnVoltar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnVoltar.Click
        Response.Redirect("AdmEvtListaEventos.aspx")
    End Sub

    Protected Sub grvPaginas_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles grvPaginas.RowEditing
        Response.Redirect("AdmEvtEditarPagina.aspx?Evento=" & lblId.Text & "&Tela=" & grvPaginas.DataKeys(e.NewEditIndex).Value.ToString())
    End Sub

    Protected Sub grvPaginas_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grvPaginas.RowDeleting
        Try
            BCTelaEvento.DeletarTela(grvPaginas.DataKeys(e.RowIndex).Value.ToString())
            InicializarAlteracaoEvento(lblId.Text)
        Catch ex As ApplicationException

        End Try
    End Sub
End Class
